//
//  CollectionCell.m
//  网易新闻
//
//  Created by dllo on 15/9/14.
//  Copyright (c) 2015年 Lx. All rights reserved.
//

#import "XWCollectionCell.h"
#import "MJRefresh.h"
#import "XWTableViewCell_a.h"
#import "XWTableViewCell_b.h"
#import "XWTableViewCell_c.h"
#import "XWTableViewCell_scoll.h"
#import "XWTableViewCell_scoll_b.h"
#import "XinwenModel.h"
#import "AFTool.h"
#import "Settings.h"
@interface XWCollectionCell()<UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)NSArray *modArr;
@property(nonatomic, assign)NSInteger cellheight;
@property(nonatomic, retain)UIButton *search;
@end
@implementation XWCollectionCell
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.cellheight = 44;
        self.backgroundColor = [UIColor whiteColor];
        [self createTableView];
    }
    return self;
}

- (void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes{
    [self.tableView.header beginRefreshing];
    self.tableView.contentOffset = CGPointMake(0, 0);
}

- (void)handelDataWithURL:(NSString *)urlStr{
    [AFTool GETWithURL:urlStr body:nil httpHead:nil responseStyle:JSON success:^(id result) {
        
        NSDictionary *tempDic = [[NSDictionary alloc]initWithDictionary:result];
        self.modArr = [[NSArray alloc]initWithArray:[tempDic objectForKey:[[tempDic allKeys]lastObject]]];
        [[Settings shareSettings]writeToDBWithDic:tempDic WithName:urlStr];
        [tempDic release];
        [self.tableView reloadData];
        
    } fail:^(NSError *error) {
        NSDictionary *tempDic = [[NSDictionary alloc]initWithDictionary:[[Settings shareSettings]dicSelectFromDB:urlStr]];
        if (![tempDic isEqual:nil]) {
            self.modArr = [[NSArray alloc]initWithArray:[tempDic objectForKey:[[tempDic allKeys]lastObject]]];
            [tempDic release];
            [self.tableView reloadData];
        }
        NSLog(@"404(XWCollectionCell)");
    }];
}

- (void)createTableView{
    self.tableView = [[UITableView alloc]initWithFrame:self.contentView.frame style:UITableViewStylePlain];
    self.tableView.backgroundColor = [[Settings shareSettings]color:WhiteToGray];
    self.tableView.center = self.contentView.center;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self notificationHandle];
    [self.contentView addSubview:self.tableView];
    [self.tableView release];
    
    [self.tableView registerClass:[XWTableViewCell_a class] forCellReuseIdentifier:@"XWTableViewCell_a"];
    [self.tableView registerClass:[XWTableViewCell_b class] forCellReuseIdentifier:@"XWTableViewCell_b"];
    [self.tableView registerClass:[XWTableViewCell_c class] forCellReuseIdentifier:@"XWTableViewCell_c"];
    
    self.tableView.tableFooterView = [[UIView alloc]init];
    
    self.search = [UIButton buttonWithType:UIButtonTypeCustom];
    self.search.frame = CGRectMake(0, 0, 375, 40);
    [self.search setBackgroundImage:[UIImage imageNamed:@"search.jpg"] forState:UIControlStateNormal];
    [self.search addTarget:self action:@selector(searchClick:) forControlEvents:UIControlEventTouchUpInside];
    self.search.backgroundColor = [UIColor redColor];
    [self.tableView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
    
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self handelDataWithURL:[self.itemURL stringByReplacingOccurrencesOfString:@"NUMBER" withString:@"20"]];
        [self.tableView.header endRefreshing];
    }];
    
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self handelDataWithURL:[self.itemURL stringByReplacingOccurrencesOfString:@"NUMBER" withString:[NSString stringWithFormat:@"%lu", self.modArr.count+20]]];
        [self.tableView.footer endRefreshing];
    }];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if (self.tableView.contentOffset.y>5) {
        self.tableView.tableHeaderView = nil;
    }
    static int i = 0;
    if (i==1&&self.tableView.dragging==0&&self.tableView.contentOffset.y<-5) {
        self.tableView.tableHeaderView = self.search;
    }
    i = self.tableView.dragging;
}

- (void)searchClick:(UIButton *)button{
    [self.delegate pushSearchView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.modArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    XinwenModel *mod = [XinwenModel modWithDic:self.modArr[indexPath.row]];
    if (mod.hasHead == 1 && (mod.ads != nil)) {
        if ([mod.alias isEqualToString:@"Top News"]) {
            XWTableViewCell_scoll *cell = [[XWTableViewCell_scoll alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"XWTableViewCell_scoll"];
            cell.mod = mod;
            self.cellheight = cell.height;
            return cell;
        }else{
            XWTableViewCell_scoll_b *cell = [[XWTableViewCell_scoll_b alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"XWTableViewCell_scoll_b"];
            cell.mod = mod;
            self.cellheight = cell.height;
            return cell;
        }
    }else if (mod.imgType.intValue == 1){
        XWTableViewCell_b *cell = [self.tableView dequeueReusableCellWithIdentifier:@"XWTableViewCell_b"];
        cell.mod = mod;
        self.cellheight = cell.height;
        return cell;
    }else if ([mod.skipType isEqualToString:@"photoset"]){
        XWTableViewCell_c *cell = [self.tableView dequeueReusableCellWithIdentifier:@"XWTableViewCell_c"];
        cell.mod = mod;
        self.cellheight = cell.height;
        return cell;
    }else{
        XWTableViewCell_a *cell = [self.tableView dequeueReusableCellWithIdentifier:@"XWTableViewCell_a"];
        cell.mod = mod;
        self.cellheight = cell.height;
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return self.cellheight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
        XinwenModel *mod = [XinwenModel modWithDic:self.modArr[indexPath.row]];
        if (mod.hasHead == 1 && (mod.ads != nil)) {
            if ([mod.alias isEqualToString:@"Top News"]) {
                
            }else{
                
            }
        }else if (mod.imgType.intValue == 1){
            [self.delegate pushDetailsViewWithDocid:mod.docid];
        }else if ([mod.skipType isEqualToString:@"photoset"]){
            [self.delegate pushDetailsViewWithSkipid:mod.skipID];
        }else{
            [self.delegate pushDetailsViewWithDocid:mod.docid];
        }
}

- (void)notificationHandle{
    [[NSNotificationCenter defaultCenter]addObserverForName:@"changeBackgroundColor" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
        self.tableView.backgroundColor = [[Settings shareSettings]color:WhiteToGray];
    }];
}

- (void)dealloc{
    _tableView.dataSource = nil;
    _tableView.delegate = nil;
    [_tableView removeObserver:self forKeyPath:@"contentOffset"];
    [_tableView release];
    [_modArr release];
    [_itemURL release];
    [super dealloc];
}

@end
